package be.kuleuven.thesis.pages;

import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import be.kuleuven.thesis.R;
import be.kuleuven.thesis.framework.Atmosphere;
import be.kuleuven.thesis.framework.Filter;
import be.kuleuven.thesis.status.PlaylistGenerator;
import be.kuleuven.thesis.widget.RangeSeekBar;
import be.kuleuven.thesis.widget.RangeSeekBar.OnRangeSeekBarChangeListener;

public class SetRadioFilters extends Activity{
	//private Filter filter;
	private PlaylistGenerator generator;
	Map<Atmosphere, ToggleButton> atmoButtons;
	RangeSeekBar<Integer> timeBar;
	RangeSeekBar<Integer> tempoBar;
	RangeSeekBar<Integer> popularityBar;
	RangeSeekBar<Integer> hardnessBar;
	Resources resources;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.set_radio_filters);
        generator = PlaylistGenerator.getInstance();
        resources = getResources();
        atmoButtons = new HashMap<Atmosphere, ToggleButton>();
        fillAtmoButtons();
        
        //filter = generator.getFilter().clone();
        
        handleButtons();
        handleAtmospheres();
        handleTimeLayout();
        handleTempoLayout();
        handlePopularityLayout();
        handleHardnessLayout();
        setStateToFilter();
        
        GenerecsTabActivity parentActivity;
        parentActivity = (GenerecsTabActivity) this.getParent().getParent();
        parentActivity.setOnTabChangedListener(new OnTabChangeListener() {		
			@Override
			public void onTabChanged(String tabId) {
				PlaylistGenerator.getInstance().applyFilter();
				Toast.makeText(getApplicationContext(), getResources().getString(R.string.changes_applied), Toast.LENGTH_SHORT).show();
				GenerecsTabActivity parentActivity;
			    parentActivity = (GenerecsTabActivity) SetRadioFilters.this.getParent().getParent();
			    parentActivity.setOnTabChangedListener(null);
			}
		});
	}
	
	private void fillAtmoButtons() {
		for(Atmosphere a: Atmosphere.values()) {
			ToggleButton button = (ToggleButton) findViewById(a.getButtonId());
			button.setTextOn(getResources().getString(a.getLabelId()));
			button.setTextOff(getResources().getString(a.getLabelId()));
			atmoButtons.put(a, button);
		}
	}
	
	@Override
	public void onResume() {
		super.onResume();
//		filter = generator.getFilter().clone();
//        setStateToFilter();
	}
	
	private Filter getFilter() {
		return generator.getFilter();
	}
	
	private void handleButtons() {
//		Button reset = (Button) findViewById(R.id.reset_filters);
//		reset.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				getFilter().reset();
//				setStateToFilter();
//			}
//		});
		
//		Button cancel = (Button) findViewById(R.id.cancel_filters);
//		cancel.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				filter = generator.getFilter();
//				setStateToFilter();
//				returnToCurrentPlaylist();
//			}
//		});
//		
//		Button apply = (Button) findViewById(R.id.apply_filters);
//		apply.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				generator.applyFilter(filter);
//				returnToCurrentPlaylist();
//			}
//		});
	}
	
	private void handleAtmospheres() {
		for(Atmosphere a: Atmosphere.values()) {
			ToggleButton button = atmoButtons.get(a);
			button.setTag(a);
			button.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Atmosphere a = (Atmosphere) v.getTag();
					if(getFilter().getAtmospheres().contains(a))
						getFilter().removeAtmosphere(a);
					else getFilter().addAtmosphere(a);
				}
			});
		}
		
		Button allButton = (Button) findViewById(R.id.all_atmospheres);
		allButton.setTag(allButton);
		allButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Button allButton = (Button) v.getTag();
				if(allButton.getText().equals(getResources().getString(R.string.enable_all))) {
					switchAllButtons(true);
					getFilter().setAtmospheres(getFilter().getAllAtmospheres());
					allButton.setText(getResources().getString(R.string.disable_all));
				} else {
					switchAllButtons(false);
					getFilter().getAtmospheres().clear();
					allButton.setText(getResources().getString(R.string.enable_all));
				}
			}
		});
		
//		ToggleButton allButton = (ToggleButton) findViewById(R.id.all_atmospheres);
//		allButton.setTag(allButton);
//		allButton.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				ToggleButton allButton = (ToggleButton) v.getTag();
//				if(allButton.isChecked()) {
//					switchAllButtons(true);
//					filter.setAtmospheres(filter.getAllAtmospheres());
//				}
//				else {
//					switchAllButtons(false);
//					filter.getAtmospheres().clear();
//				}
//			}
//		});
	}
	
	private void switchAllButtons(boolean flag) {
		for(Atmosphere a: Atmosphere.values()) {
			ToggleButton button = atmoButtons.get(a);
			button.setChecked(flag);
		}
	}
	
//	private void returnToCurrentPlaylist() {
//		Intent i = new Intent(SetRadioFilters.this, CurrentPlaylist.class);
//		View view = CurrentPlaylistGroup.group.getLocalActivityManager()
//		        		.startActivity("Set Radio Filters", i
//		        		.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
//		        		.getDecorView();
//		CurrentPlaylistGroup.group.replaceView(view);
//	}
	
	private void setStateToFilter() {
		for(Atmosphere a: Atmosphere.values()) {
			ToggleButton button = atmoButtons.get(a);
			if(getFilter().getAtmospheres().contains(a))
				button.setChecked(true);
			else button.setChecked(false);
		}
		timeBar.setSelectedMinValue(getFilter().getMinYear());
		timeBar.setSelectedMaxValue(getFilter().getMaxYear());
		tempoBar.setSelectedMinValue(getFilter().getMinTempo());
		tempoBar.setSelectedMaxValue(getFilter().getMaxTempo());
		popularityBar.setSelectedMinValue(getFilter().getMinPop());
		popularityBar.setSelectedMaxValue(getFilter().getMaxPop());
		hardnessBar.setSelectedMinValue(getFilter().getMinHard());
		hardnessBar.setSelectedMaxValue(getFilter().getMaxHard());
	}
	
	private void handleTimeLayout() {
		TextView yearLabel = (TextView) findViewById(R.id.year_label);
		String min = (String) (getFilter().getMinYear() == 1949 ? "1889" : getFilter().getMinYear()+"");
		yearLabel.setText(resources.getString(R.string.period)+min+" - "+getFilter().getMaxYear());
		
		final Handler timeHandler = new Handler() {
            @Override
            public void handleMessage(Message message) {
            	TextView yearLabel = (TextView) findViewById(R.id.year_label);
            	int min = message.arg1;
            	int max = message.arg2;
            	String minString = (String) (min == 1949 ? "1889" : min+"");
        		yearLabel.setText(resources.getString(R.string.period)+minString+" - "+max);
            }
        };
        
        // create RangeSeekBar as Integer range between 20 and 75
        timeBar = new RangeSeekBar<Integer>(Filter.MIN_YEAR, Filter.MAX_YEAR, this, R.drawable.timebar2, timeHandler);
        timeBar.setOnRangeSeekBarChangeListener(new OnRangeSeekBarChangeListener<Integer>() {
                @Override
                public void rangeSeekBarValuesChanged(Integer minValue, Integer maxValue) {
                	getFilter().setMinYear(minValue);
                	getFilter().setMaxYear(maxValue);
                }
        });

        // add RangeSeekBar to pre-defined layout
        ViewGroup layout = (ViewGroup) findViewById(R.id.year_layout);
        layout.addView(timeBar);
	}
	
	private void handleTempoLayout() {
		TextView tempoLabel = (TextView) findViewById(R.id.tempo_label);
    	tempoLabel.setText(resources.getString(R.string.tempo)+getFilter().getMinTempo()+"bpm - "+getFilter().getMaxTempo()+"bpm");
    	
		final Handler tempoHandler = new Handler() {
            @Override
            public void handleMessage(Message message) {
            	TextView tempoLabel = (TextView) findViewById(R.id.tempo_label);
            	int min = message.arg1;
            	int max = message.arg2;
            	tempoLabel.setText(resources.getString(R.string.tempo)+min+"bpm - "+max+"bpm");
            }
        };
        
		// create RangeSeekBar as Integer range between 20 and 75
        tempoBar = new RangeSeekBar<Integer>(Filter.MIN_TEMPO, Filter.MAX_TEMPO, this, 0, tempoHandler);
        tempoBar.setOnRangeSeekBarChangeListener(new OnRangeSeekBarChangeListener<Integer>() {
                @Override
                public void rangeSeekBarValuesChanged(Integer minValue, Integer maxValue) {
                	getFilter().setMinTempo(minValue);
                	getFilter().setMaxTempo(maxValue);
                }
        });

        // add RangeSeekBar to pre-defined layout
        ViewGroup layout = (ViewGroup) findViewById(R.id.tempo_layout);
        layout.addView(tempoBar);
	}
	
	private void handlePopularityLayout() {
		TextView popularityLabel = (TextView) findViewById(R.id.popularity_label);
    	popularityLabel.setText(resources.getString(R.string.popularity)+getFilter().getMinPop()+" - "+getFilter().getMaxPop());
    	
		final Handler popularityHandler = new Handler() {
            @Override
            public void handleMessage(Message message) {
            	TextView popularityLabel = (TextView) findViewById(R.id.popularity_label);
            	int min = message.arg1;
            	int max = message.arg2;
            	popularityLabel.setText(resources.getString(R.string.popularity)+" "+min+" - "+max);
            }
        };
        
		// create RangeSeekBar as Integer range between 20 and 75
        popularityBar = new RangeSeekBar<Integer>(Filter.MIN_POP, Filter.MAX_POP, this, 0, popularityHandler);
        popularityBar.setOnRangeSeekBarChangeListener(new OnRangeSeekBarChangeListener<Integer>() {
                @Override
                public void rangeSeekBarValuesChanged(Integer minValue, Integer maxValue) {
                	getFilter().setMinPop(minValue);
                	getFilter().setMaxPop(maxValue);
                }
        });

        // add RangeSeekBar to pre-defined layout
        ViewGroup layout = (ViewGroup) findViewById(R.id.popularity_layout);
        layout.addView(popularityBar);
	}
	
	private void handleHardnessLayout() {
		TextView hardnessLabel = (TextView) findViewById(R.id.hardness_label);
    	hardnessLabel.setText(resources.getString(R.string.hardness)+getFilter().getMinHard()+" - "+getFilter().getMaxHard());
    	
		final Handler hardnessHandler = new Handler() {
            @Override
            public void handleMessage(Message message) {
            	TextView hardnessLabel = (TextView) findViewById(R.id.hardness_label);
            	int min = message.arg1;
            	int max = message.arg2;
            	hardnessLabel.setText(resources.getString(R.string.hardness)+" "+min+" - "+max);
            }
        };
        
		// create RangeSeekBar as Integer range between 20 and 75
        hardnessBar = new RangeSeekBar<Integer>(Filter.MIN_HARD, Filter.MAX_HARD, this, 0, hardnessHandler);
        hardnessBar.setOnRangeSeekBarChangeListener(new OnRangeSeekBarChangeListener<Integer>() {
                @Override
                public void rangeSeekBarValuesChanged(Integer minValue, Integer maxValue) {
                	getFilter().setMinPop(minValue);
                	getFilter().setMaxPop(maxValue);
                }
        });

        // add RangeSeekBar to pre-defined layout
        ViewGroup layout = (ViewGroup) findViewById(R.id.hardness_layout);
        layout.addView(hardnessBar);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		System.out.println("HALLOA");
		menu.clear();
		return true;
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		System.out.println("HONOLULU");
		return true;
	}
	
	@Override
	public void onBackPressed() {
		System.out.println("Hawai");
	}
}
